package com.hiutil.sql;

import java.util.List;
import java.util.function.Function;

import com.hiutil.cbo.MethodsFactory;

/**
 * 使用参数创建SQL语句,参数以@标识
 * @author xuminrong
 *
 */
public class SQLHelper {
	/**
	 * 根据参数创建SQL语句
	 * @param sql  含以@为参数的SQL语句
	 * @param callback
	 * @return
	 */
	public static String createSQLByParams(String sql, Function<String, String> callback) {
		if (null == callback) {
			return sql;
		}
		List<SQLStr> lst = SQLParser.Parase(sql);
		if (lst == null) {
			return sql;
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < lst.size(); i++) {
			SQLStr info = lst.get(i);
			if (!info.isParam()) {
				sb.append(info.getText());
				continue;
			}
			if (callback == null) {
				return "";
			}
			String ret = callback.apply(info.getValue());
			sb.append(ret == null? "": ret);
		}
		return sb.toString();
	}

	/**
	 * 使用对象创建SQL语句
	 * @param sql
	 * @param t
	 * @param type
	 * @return
	 */
	public static <T> String createSQLByObject(String sql,  T t, Class<T> type) {
		if (null == t) {
			return sql;
		}

		return createSQLByParams(sql, (key)-> {
			String val = MethodsFactory.getPropertyValue(t, key, type);
			if (null == val) {
				return "";
			}
			return val;
		});
	}
}
